package com.ruoyi.project.schedule.task.service;


import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.schedule.task.domain.Task;
import com.ruoyi.project.schedule.task.mapper.TaskMapper;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 任务管理业务层
 */
@Service
public class TaskServiceImpl implements ITaskService {


    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private IUserService iUserService;

    /**
     * 显示所有任务列表（创建者）
     *
     * @return
     */
    @Override
    public List<Task> selectTaskList(Task task) {
        task.setTaskCreateId(ShiroUtils.getUserId());
        return taskMapper.selectTaskList(task);
    }

    /**
     * 显示所有任务列表（完成者）
     *
     * @return
     */
    @Override
    public List<Task> selectTaskListFinished(Task task) {
        task.setTaskUserId(ShiroUtils.getUserId());
        return taskMapper.selectTaskList(task);
    }

    /**
     * 创建任务
     *
     * @param task
     * @return
     */
    @Override
    public AjaxResult insertTask(Task task) {
        Date date = new Date();

        User user = iUserService.selectUserById(task.getTaskUserId());
        task.setTaskUser(user.getUserName());
        task.setTaskCreateName(ShiroUtils.getLoginName());
        task.setTaskCreateId(ShiroUtils.getUserId());
        task.setTaskCreateTime(date);
        task.setTaskStatus(0);
        int i = taskMapper.insertTask(task);
        if (i == 1) {
            return AjaxResult.success("创建任务成功");
        }
        return AjaxResult.error("创建任务失败");
    }

    /**
     * 查询特定部门所有用户
     *
     * @param user
     * @return
     */
    @Override
    public List<User> selectUser(User user) {
        List<User> list = iUserService.selectUserList(user);
        //清空密码
        for (int i = 0; i < list.size(); i++) {
            User user1 = list.get(i);
            user1.setPassword(null);
        }
        return list;
    }

    /**
     * 根据taskId查询任务信息
     * @param taskId
     * @return
     */
    public Task selectByTaskId(Long taskId){
        return taskMapper.selectTaskById(taskId);
    }

    /**
     * 批量删除任务
     *
     * @param taskIds
     * @return
     * @throws Exception
     */
    @Override
    public int deleteTaskByIds(String taskIds) {

        String[] userIds = Convert.toStrArray(taskIds);

        return taskMapper.deleteTaskByIds(userIds);
    }

    /**
     * 完成任务
     * @param task
     * @return
     */
    @Override
    public AjaxResult updateTaskBy(Task task) {

        int i = taskMapper.updateTask(task);

        if (i == 1) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }



}
